package com.sdruixinggroup.mondayb2b.widget;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.reflect.TypeToken;
import com.sdruixinggroup.mondayb2b.API.API;
import com.sdruixinggroup.mondayb2b.R;
import com.sdruixinggroup.mondayb2b.interfaces.ObjectCallBack;
import com.sdruixinggroup.mondayb2b.models.ModelBeen;
import com.sdruixinggroup.mondayb2b.models.QuickOrder;
import com.sdruixinggroup.mondayb2b.models.ShoppingCartBeen;
import com.sdruixinggroup.mondayb2b.ui.WebActivity;
import com.sdruixinggroup.mondayb2b.utils.UserInfoUtil;
import com.squareup.picasso.Picasso;
import com.zhy.http.okhttp.OkHttpUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.math.BigDecimal;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

import static com.sdruixinggroup.mondayb2b.ui.fragments.ShoppingCartFragment.REFLUSH_COUNT;
import static com.sdruixinggroup.mondayb2b.ui.fragments.ShoppingCartFragment.REFLUSH_SELECT_COUNT;
import static com.sdruixinggroup.mondayb2b.utils.DisplayUtil.double2String;

/**
 * Created by 00029935 on 2017/11/19.
 */

public class MineGoodsView extends AbCustomHeaderView {
    @BindView(R.id.cb_box)
    TextView cbBox;
    @BindView(R.id.iv_good_pic)
    ImageView ivGoodPic;
    @BindView(R.id.tv_message)
    TextView tvMessage;
    @BindView(R.id.tv_price)
    TextView tvPrice;
    @BindView(R.id.tv_count)
    TextView tvCount;
    @BindView(R.id.rl_minus)
    RelativeLayout rlMinus;
    @BindView(R.id.rl_add)
    RelativeLayout rlAdd;
    @BindView(R.id.ll_change_count)
    LinearLayout llChangeCount;
    @BindView(R.id.iv_delete)
    ImageView ivDelete;
    @BindView(R.id.tv_count_my)
    EditText tvCountMy;
    @BindView(R.id.rl_content)
    RelativeLayout rlContent;
    private int count = 0;
    private Boolean isQuickOreder= false;
    private InputMethodManager imm;
    private ShoppingCartBeen.MerchantsBean.ShoppingCartsBean shoppingCartsBean;

    public MineGoodsView(Context context) {
        super(context);
    }

    public MineGoodsView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public MineGoodsView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public static final int FINISH_EDITOR=0x10;
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(Object resp) {/* Do something */
            Log.e("HQQ","onMessageEventggg: ");
        if (resp instanceof Integer) {

            int params = (Integer) resp;
            switch (params){
                case FINISH_EDITOR:
                        //  resourceEtSearch.setVisibility(View.GONE);
                        imm.hideSoftInputFromWindow(tvCountMy.getApplicationWindowToken(), 0);
                        ((Activity)getContext()).getWindow().setSoftInputMode(
                                WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
                        Log.e("HQQ","count : "+count);
                       // changGoodsCount(shoppingCartsBean.getShopping_cart_id(), count);
                       // shoppingCartsBean.setQuantity(count);

                    break;
            }
        }

    }

    @Override
    public int getInflateLayout() {
        return R.layout.mine_goods_view;
    }

    @Override
    public void setUpView(View view) {
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        rlMinus.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                onViewClicked(v);
            }
        });

        rlAdd.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                onViewClicked(v);
            }
        });


        cbBox.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {

                shoppingCartsBean.isSelect = !shoppingCartsBean.isSelect;
                cbBox.setSelected(shoppingCartsBean.isSelect);
                EventBus.getDefault().post(REFLUSH_SELECT_COUNT);
                if(lisntener!=null){
                    lisntener.onChecked();
                }
            }
        });

        tvCountMy.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {

                if (actionId == EditorInfo.IME_ACTION_SEND
                        || (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                    String key = v.getText().toString().trim();
                    if (!TextUtils.isEmpty(key)) {
                        //  resourceEtSearch.setVisibility(View.GONE);
                        imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);
                        ((Activity)getContext()).getWindow().setSoftInputMode(
                                WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
                        count =Integer.valueOf(key);
                        changGoodsCount(shoppingCartsBean.getShopping_cart_id(), count);
                        shoppingCartsBean.setQuantity(count);
                    } else {
                        Toast.makeText(getContext(), "请输入数量", Toast.LENGTH_SHORT).show();
                    }

                    return true;
                }

                return false;
            }
        });

        tvCountMy.addTextChangedListener(new TextWatcher(){
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if(!isQuickOreder){
                    String key = tvCountMy.getText().toString().trim();
                    if (!TextUtils.isEmpty(key)) {
                       // count = Integer.valueOf(tvCountMy.getText().toString().trim());
                        BigDecimal bigDecimal = new BigDecimal(tvCountMy.getText().toString().trim());
                        count= bigDecimal.intValue();
                        if(count<10000){
                            changGoodsCount(shoppingCartsBean.getShopping_cart_id(), count);
                            shoppingCartsBean.setQuantity(count);
                        }

                    }
                }
            }
        });
    }

    public void update( ShoppingCartBeen.MerchantsBean.ShoppingCartsBean shoppingCartsBean) {
        this.shoppingCartsBean = shoppingCartsBean;
        Picasso.with(getContext()).load(shoppingCartsBean.getGoods().getThumb()).error(R.mipmap.collect_merchandise).into(ivGoodPic);
        ivGoodPic.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                String params = "productdetail"+"?goods_id="+MineGoodsView.this.shoppingCartsBean.getGoods().getGoods_id()+"&area_id="+ UserInfoUtil.AREA_CODE +"&latitude="+UserInfoUtil.mLatitude
                        +"&longitude="+UserInfoUtil.mLongitude;
                if(!MineGoodsView.this.shoppingCartsBean.isEditabe){
                    toWebView(params);
                }

            }
        });
        tvMessage.setText(shoppingCartsBean.getGoods().getName());
        tvPrice.setText("¥ " + double2String(shoppingCartsBean.getGoods().getSale_price()));
        tvCount.setText("×" + String.valueOf(shoppingCartsBean.getQuantity()));
        count = shoppingCartsBean.getQuantity();
        tvCountMy.setText(String.valueOf(count));

        cbBox.setSelected(shoppingCartsBean.isSelect);
        if (shoppingCartsBean.isEditabe) {
            cbBox.setVisibility(GONE);
            ivDelete.setVisibility(VISIBLE);
            llChangeCount.setVisibility(VISIBLE);
        } else {
            cbBox.setVisibility(VISIBLE);
            ivDelete.setVisibility(GONE);
            llChangeCount.setVisibility(GONE);
        }

        rlContent.setVisibility(shoppingCartsBean.inVisiableCheckView ?GONE:VISIBLE);
    }

    public void quicksetData(QuickOrder  goodsBean){
        isQuickOreder = true;
        Picasso.with(getContext()).load(goodsBean.getGoods().getThumb()).error(R.mipmap.collect_merchandise).into(ivGoodPic);
        tvMessage.setText(goodsBean.getGoods().getName());
        tvPrice.setText("¥ " + String.valueOf(goodsBean.getGoods().getSale_price()));
        tvCount.setText("×" + String.valueOf(goodsBean.getQuantity()));
        tvCountMy.setText(String.valueOf(goodsBean.getQuantity()));

        cbBox.setVisibility(VISIBLE);
        ivDelete.setVisibility(GONE);
        llChangeCount.setVisibility(GONE);
        rlContent.setVisibility(GONE);
    }

    @OnClick({R.id.rl_minus, R.id.rl_add})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_minus:
                if (count > 1) {
                    --count;
                }
                break;
            case R.id.rl_add:
                ++count;
                break;
        }
        tvCount.setText("×" + String.valueOf(count));
        tvCountMy.setText(String.valueOf(count));
        shoppingCartsBean.setQuantity(count);
        changGoodsCount(shoppingCartsBean.getShopping_cart_id(), count);
    }

    @OnClick(R.id.iv_delete)
    public void onViewClicked() {
        showDialog(shoppingCartsBean.getShopping_cart_id());
    }


    private void changGoodsCount(int shopping_cart_id, int quantity) {
        String url = API.SHOPPING_CART + shopping_cart_id + "/quantity?quantity=" + quantity + "&access_token=" + UserInfoUtil.getInfoToken(getContext());
        HashMap<String, String> headers = new HashMap<>();
        headers.put("Accept", "*/*");

        TypeToken<ModelBeen> typeToken = new TypeToken<ModelBeen>() {
        };
        OkHttpUtils.post().url(url).headers(headers).build().execute(new ObjectCallBack<ModelBeen>(typeToken) {
            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(ModelBeen response, int id) {
                if (response.err_code == 0) {

                } else {
                   // showMsgToast(response.err_msg);
                }
            }
        });
    }


    private void showDialog(final int shopping_cart_id) {
        AlertDialog dialog = new AlertDialog.Builder(getContext()).setTitle("提示")
                .setMessage("您确定要删除这个商品吗？")
                .setNeutralButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                }).setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        queryData(shopping_cart_id);
                    }
                }).create();

        dialog.show();
    }

    private void queryData(final int shopping_cart_id) {
        String url = API.SHOPPING_CART + shopping_cart_id + "/delete?access_token=" + UserInfoUtil.getInfoToken(getContext());
        HashMap<String, String> headers = new HashMap<>();
        headers.put("Accept", "*/*");

        TypeToken<ModelBeen> typeToken = new TypeToken<ModelBeen>() {
        };
        OkHttpUtils.post().url(url).headers(headers).build().execute(new ObjectCallBack<ModelBeen>(typeToken) {
            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(ModelBeen response, int id) {
                if (response.err_code == 0) {
                    showMsgToast("删除成功！");
                    EventBus.getDefault().post(REFLUSH_COUNT);
                } else {
                    showMsgToast(response.err_msg);
                }
            }
        });
    }


    private void toWebView(String param) {
        Intent intent = new Intent(getContext(), WebActivity.class);
        intent.putExtra(WebActivity.INTENT_EXTRA_BEGIN_URL, param);
        getContext().startActivity(intent);
    }


    public  interface  MyCheckedChangeLisntener{
        public void onChecked();
    }


    private MyCheckedChangeLisntener lisntener;

    public void setMyCheckedChangeLisener(MyCheckedChangeLisntener lisener){
        this.lisntener=lisener;
    }
}
